import path from 'node:path';
import {fileURLToPath} from "node:url";
import nodeResolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import ts from '@rollup/plugin-typescript';
import inject from '@rollup/plugin-inject';
import typescript from 'typescript';
import terser from '@rollup/plugin-terser';
import babel from '@rollup/plugin-babel';
import json from '@rollup/plugin-json';
import externals from "rollup-plugin-node-externals";
import postcss from 'rollup-plugin-postcss';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const resolve = _path => path.resolve(__dirname, _path);
const extensions = [ '.js', '.ts', '.tsx' ];

// console.log('WIDGET_NAME', process.env)

export default {
  input: `src/widget/${process.env.WIDGET_PATH}/index.tsx`, // 打包入口
  output: [
    { // 打包出口
      file: `dist/${process.env.WIDGET_PATH}.esm.mjs`, // 最终打包出来的文件路径和文件名，这里是在package.json的browser:
      // 'dist/index.js'字段中配置的
      // name: 'named',
      format: 'esm', // umd是兼容amd/cjs/iife的通用打包格式，适合浏览器
      // entryFileNames: '[name].esm.js',
      sourcemap: false, // 是否输出sourcemap
    },
    {
      dir: 'dist',
      format: 'umd',
      entryFileNames: `${process.env.WIDGET_PATH}.js`,
      name: `$${process.env.WIDGET_PATH.toLocaleLowerCase()}`, // umd 模块名称，相当于一个命名空间，会自动挂载到window下面
      sourcemap: false,
    },
  ],

  // 不能使用正则匹配
  // external: ['react', 'react-dom'],

  plugins: [ // 打包插件
    json(),
    // nodeResolve(), // 查找和打包node_modules中的第三方模块
    commonjs(), // 将 CommonJS 转换成 ES2015 模块供 Rollup 处理
    // 注入 React
    inject({
      include: ['**/*.tsx'],
      React: 'React',
      widgets: 'widgets',
      utils: 'utils',
    }),
    postcss({
      extract: false,
      modules: false,
      use: ['less'],
    }),
    externals({
      devDeps: false, // devDependencies 类型的依赖就不用加到 externals 了。
    }),
    // 解析TypeScript
    ts({
      typescript,
      exclude: "node_modules/**",
      tsconfig: resolve('tsconfig.rullop.json'),
      compilerOptions: {
        rootDir: `src/widget/${process.env.WIDGET_PATH}`,
        outDir: 'dist',
        // sourcemap: false,
        // declaration: true,
        // declarationDir: "lib",
      },
    }),
    babel({ exclude: '**/node_modules/**', runtimeHelpers: true }),
    // uglify(),
  ]
};
